package classfile

type LocalVariableTableAttr struct {
	AttrStruct
	localVariableTableLength uint16
	localVariableTables      []LocalVariableTable
}

type LocalVariableTable struct {
	// 变量开始生效的行
	startPc uint16
	// 变量影响范围
	length uint16
	// 变量名称
	localVariableNameIndex uint16
	localVariableName      Constant
	// 变量类型描述
	localVariableDescriptorIndex uint16
	localVariableDescriptor      Constant
	// 序号
	localVariableIndex uint16
}

func (self *LocalVariableTableAttr) readAttr(cp ConstantPool) AttributeInfo {
	self.localVariableTableLength = self.attributeData.ReadUInt16()
	if self.localVariableTableLength > 0 {
		self.localVariableTables = make([]LocalVariableTable, self.localVariableTableLength)
		for i := 0; i < int(self.localVariableTableLength); i++ {
			self.localVariableTables[i] = NewLocalVariableTable(&self.attributeData, cp)
		}
	}
	return self
}

func NewLocalVariableTable(data *AttributeData, cp ConstantPool) LocalVariableTable {
	startPc := data.ReadUInt16()
	length := data.ReadUInt16()
	localVariableNameIndex := data.ReadUInt16()
	localVariableDescriptorIndex := data.ReadUInt16()
	localVariableName := cp.GetConstant(localVariableNameIndex)
	localVariableDescriptor := cp.GetConstant(localVariableDescriptorIndex)
	localVariableIndex := data.ReadUInt16()
	return LocalVariableTable{startPc, length, localVariableNameIndex, localVariableName,
		localVariableDescriptorIndex, localVariableDescriptor, localVariableIndex,
	}
}
